


"""下面的例子是通过定义一个类来实现python里面封装的各类魔术方法，备不时之需"""

class MagicMethod(object):

    def __new__(cls, *args, **kwargs):
        print('__new__')

    def __init__(self,start=0,step=1):
        print('__init__')
        self.start = start
        self.step = step
        self.data = {}

    def __getitem__(self, item):
        print('__getitem__')
        try:
            return self.data[item]
        except KeyError:
            return self.start+self.step

    def __setitem__(self, key, value):
        print('__setitem__')
        self.data[key]=value

    def __len__(self):
        print('__len__')
        return len(self.data)+1

    def __delitem__(self, key):
        print('__delitem__')
        del self.data[key]

    def __call__(self, *args, **kwargs):
        print('__call__')

    def __del__(self):
        print('__del__')

    def __str__(self):
        print('__str__')

    def __repr__(self):
        print('__repr')

    def __iter__(self):
        print('__iter__')




magic = MagicMethod(1,2)
print(magic[3])
magic[3]=100
print(magic[3])
print(len(magic))
del magic[3]